package com.bright.ghj.overt.repository.primary;

import com.bright.ghj.overt.pojo.po.primary.AsyncMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Tz
 * @date 2024/01/22 15:03
 * @Description 异步消息记录信息的 Repository
 */
public interface AsyncMessageRepository extends JpaRepository<AsyncMessage, Integer>, JpaSpecificationExecutor<AsyncMessage> {


    /**
     * 根据id撤回当前任务
     *
     * @param id 主键id
     * @return   返回结果数
     */
    @Transactional(rollbackFor = Throwable.class)
    @Modifying
    @Query("update AsyncMessage set execStatus = -2, runFlag = false where id = :id and runFlag = true and execFlag = false ")
    Integer revokeAsyncTask(@Param("id") Integer id);

    /**
     * 根据keyword集合查询异步消息列表
     *
     * @param keywords keyword集合
     * @return         异步消息列表
     */
    @Query("from AsyncMessage where keyword in (:keywords)")
    List<AsyncMessage> listAsyncMessageByKeywords(@Param("keywords") List<String> keywords);

    /**
     * 一键已读
     *
     * @param execStatus 需要已读的状态列表
     * @param username   需要已读的用户
     * @return 已读记录数
     */
    @Transactional(rollbackFor = Throwable.class)
    @Modifying
    @Query("update AsyncMessage set readFlag = true where execStatus in (:execStatus) and username = :username and readFlag = false ")
    Integer oneClickRead(@Param("execStatus") List<Integer> execStatus, @Param("username") String username);


    /**
     * 阅读一条未读消息
     *
     * @param id 主键
     * @return 读取结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Modifying
    @Query("update AsyncMessage set readFlag = true where id = :id and readFlag = false ")
    Integer read(@Param("id") Integer id);
}
